#pragma once

#include <chrono>
#include <csignal>
#include <map>
#include "arrow/log.h"
#include "nlohmann/json.hpp"
#include "server/config/config.h"
#include "state_machin_define.h"


namespace ArrowWebCodeView
{
namespace SessionMachine
{

class StateCheckPassword : public StateBase
{
private:
    using Data = StateBase::Data;
    using StateEnum = StateBase::StateEnum;
    using Msg = StateBase::Msg;
    using ContextType = StateBase::ContextType;

public:
    StateCheckPassword() {}

public:
    virtual ~StateCheckPassword() {}

    /**
     * @description: 初始化 创建状态的时候调用一次
     * @param {AreaMachineData&} data
     * @return {*}
     */
    virtual void Init(const Data& data)
    {
    }

    /**
     * @description: 当从其他状态迁移到当前状态调用
     * @param {AreaMachineData*} pData
     * @return {*}
     */
    virtual void Start(Data* pData)
    {
    }

    /**
     * @description: 处理消息
     * @param {Data*} pData
     * @param {Msg} msg
     * @return {*}
     */
    virtual StateEnum HandleMsg(Data* pData, Msg msg, const std::string& strMsg, std::string& strResult)
    {
        if (msg != Msg::Login)
            return StateEnum::CheckPassword;

        if (strMsg == AppConfig::Instance()->Password())
        {
            m_pContext->ChangeState(StateEnum::RecvPath);
            nlohmann::json j;
            j["cmd"] = MsgEnumStr::ItemStr(msg);
            j["result"]["token"] = AppConfig::Instance()->GenerateToken();
            j["result"]["msg"] = "success";
            strResult = j.dump();
            ARROW_LOG_INFO("longin password success");
            return StateEnum::RecvPath;
        }

        if (AppConfig::Instance()->CheckToken(strMsg))
        {
            m_pContext->ChangeState(StateEnum::RecvPath);
            nlohmann::json j;
            j["cmd"] = MsgEnumStr::ItemStr(msg);
            j["result"]["token"] = strMsg;
            j["result"]["msg"] = "success";
            strResult = j.dump();
            ARROW_LOG_INFO("longin token success");
            return StateEnum::RecvPath;
        }

        return StateEnum::CheckPassword;
    }

    /**
     * @description: 处理定时消息
     * @param {AreaMachineData*} pData
     * @return {*}
     */
    virtual StateEnum Timer(Data* pData)
    {
        return State();
    }

    /**
     * @description: 当前状态
     * @return {*}
     */
    virtual StateEnum State()
    {
        return StateEnum::CheckPassword;
    }

    virtual void Context(ContextType* pContext)
    {
        m_pContext = pContext;
    }

private:
    ContextType* m_pContext = nullptr;

};
}
}